package net.jadoth.sqlengine.interfaces;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import net.jadoth.sqlengine.internal.DatabaseGateway;


public interface SqlExecutor<R>
{	
	public R execute(DatabaseGateway<?> dbc, Statement statement, String sqlStatment) throws SQLException;
	
	
	public static final SqlExecutor<Integer> update = new SqlExecutor<Integer>() {
		@Override
		public Integer execute(DatabaseGateway<?> dbc, Statement statement, String sqlStatment) throws SQLException
		{
			if(statement == null){
				statement = dbc.getConnection().createStatement();
			}
			return statement.executeUpdate(sqlStatment);
		}
	};
	
	public static final SqlExecutor<ResultSet> query = new SqlExecutor<ResultSet>() {
		@Override
		public ResultSet execute(DatabaseGateway<?> dbc, Statement statement, String sqlStatment) throws SQLException
		{
			if(statement == null){
				statement = dbc.getConnection().createStatement();
			}
			return statement.executeQuery(sqlStatment);
		}
	};
	
	public static final SqlExecutor<Object> singleResultQuery = new SqlExecutor<Object>() {
		@Override
		public Object execute(DatabaseGateway<?> dbc, Statement statement, String sqlStatment) throws SQLException
		{
			final ResultSet rs = query.execute(dbc, statement, sqlStatment);
			try {
				if(!rs.next()) return null;
				return rs.getObject(1);
			}
			finally{
				if(rs != null){
					try {
						rs.close();
					}
					catch(final SQLException e) {
						throw dbc.getDbmsAdaptor().parseSqlException(e);
					}
				}
			}
		}
	};
}
